package com.xtgg.more;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.RequestParams;
import com.xtgg.R;
import com.xtgg.login.LoginActivity;
import com.xtgg.main.SearchBabyActivity;
import com.xtgg.main.SearchWebActivity;
import com.xtgg.manager.BaseActivity;
import com.xtgg.model.Resp;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.ImageLoaderHelper;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.TLog;
import com.xtgg.util.ToastUtil;

import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class LoseListActivity extends BaseActivity implements OnClickListener {
	MyAdapter mAdapter;
	ArrayList<JSONObject> mArray = new ArrayList<JSONObject>();
	ArrayList<String> mSelectArray = new ArrayList<String>();
	ArrayList<String> mSelectDevice = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_message_center);

		((TextView) findViewById(R.id.center)).setText("寻人记录");
		findViewById(R.id.left).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});

		final PullToRefreshListView ptrlvHeadlineNews = (PullToRefreshListView) findViewById(R.id.listview);
		ptrlvHeadlineNews
				.setMode(com.handmark.pulltorefresh.library.PullToRefreshBase.Mode.DISABLED);
		ptrlvHeadlineNews
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						sendHttpRequest();
					}
				});

		ListView listview = ptrlvHeadlineNews.getRefreshableView();
		mAdapter = new MyAdapter();
		listview.setAdapter(mAdapter);
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				JSONObject item = mArray.get(arg2 - 1);
				if (findViewById(R.id.bottom).getVisibility() == View.VISIBLE) {
					if (mSelectArray.contains(item.getString("infoid"))) {
						mSelectArray.remove(item.getString("infoid"));
					} else {
						mSelectArray.add(item.getString("infoid"));
					}
					
					if (mSelectDevice.contains(item.getString("deviceid"))) {
						mSelectDevice.remove(item.getString("deviceid"));
					} else {
						mSelectDevice.add(item.getString("deviceid"));
					}
					
					mAdapter.notifyDataSetChanged();
					return;
				}
				
				Intent intent = new Intent(LoseListActivity.this,SearchBabyActivity.class);
				intent.putExtra("baby", JSON.toJSONString(mArray.get(arg2 - 1)));
				startActivity(intent);
			}
		});
	}
	
	protected void onResume()
	{
		super.onResume();
		reloadData();
	}

	class MyAdapter extends BaseAdapter {
		public int getCount() {
			return mArray.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			FoodHolder foodHold = null;

			if (convertView == null) {
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				foodHold = new FoodHolder();

				convertView = mInflater.inflate(R.layout.item_lose, null);
				foodHold.check = (ImageView) convertView.findViewById(R.id.check);
				foodHold.img = (ImageView) convertView.findViewById(R.id.img);
				foodHold.name = (TextView) convertView.findViewById(R.id.name);
				foodHold.status = (TextView) convertView
						.findViewById(R.id.status);

				convertView.setTag(foodHold);
			} else {
				foodHold = (FoodHolder) convertView.getTag();
			}

			JSONObject item = mArray.get(position);
			foodHold.name.setText(item.getString("childname"));
			foodHold.status.setText(item.getIntValue("status") == 0 ? "已发布"
					: "已撤回");
			foodHold.status
					.setTextColor(item.getIntValue("status") == 0 ? Color
							.parseColor("#fb4e24") : Color
							.parseColor("#cccccc"));

			JSONArray list = item.getJSONArray("infopic");
			if (list.size() > 0) {
				ImageLoaderHelper.displayImage(R.drawable.img_default,
						foodHold.img, list.getJSONObject(0).getString("path"),
						20);
			} else {
				foodHold.img.setImageResource(R.drawable.img_default);
			}
			
			foodHold.check.setVisibility(View.GONE);
			if (findViewById(R.id.bottom).getVisibility() == View.VISIBLE) {
				if (mSelectArray.contains(item.getString("infoid"))) {
					foodHold.check.setImageResource(R.drawable.ic_msg_on);
				} else {
					foodHold.check.setImageResource(R.drawable.ic_msg_off);
				}
				foodHold.check.setVisibility(View.VISIBLE);
			} 

			return convertView;
		}
	}

	public final class FoodHolder {
		public ImageView check;
		public ImageView img;
		public TextView name;
		public TextView status;
	}

	public void reloadData() {
		mArray.removeAll(mArray);
		sendHttpRequest();
	}

	private void sendHttpRequest() {
		boolean show = true;
		if (mArray.size() > 0)
			show = false;
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, show, false) {
			@Override
			public void onSuccess(String response) {
				Resp ruser = JSON.parseObject(response, Resp.class);

				if (ruser.getState().equals("1")) {
					mArray.addAll(ruser.data);
					mAdapter.notifyDataSetChanged();
					
					findViewById(R.id.right).setOnClickListener(LoseListActivity.this);
					((Button) findViewById(R.id.right)).setText("编辑");
				}
				else if (ruser.getState().equals("2")) 
				{showExitDialog();} 
				else {
					findViewById(R.id.tip).setVisibility(View.VISIBLE);

					findViewById(R.id.right).setOnClickListener(null);
					((Button) findViewById(R.id.right)).setText("");
				}

				((PullToRefreshListView) findViewById(R.id.listview))
						.onRefreshComplete();
			}
		};

		RequestParams params = new RequestParams();
		params.put("act", "myInfo");
		params.put("userid", PreferencesUtils.getString(this, "userid"));

		MgqRestClient.post(Constants.INFOMGT, params, loginHandler);
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.left:
			finish();
			break;

		case R.id.right:
			if (findViewById(R.id.bottom).getVisibility() == View.VISIBLE)
				findViewById(R.id.bottom).setVisibility(View.GONE);
			else
				findViewById(R.id.bottom).setVisibility(View.VISIBLE);
			
			findViewById(R.id.del).setVisibility(View.INVISIBLE);
			findViewById(R.id.unread).setVisibility(View.INVISIBLE);
			findViewById(R.id.delete).setVisibility(View.VISIBLE);
			findViewById(R.id.delete).setOnClickListener(this);
			mAdapter.notifyDataSetChanged();
			break;
			
		case R.id.delete:
			if (mSelectArray.size() == 0) {
				ToastUtil.showToastWithAlertPic("请选择操作项");
				return;
			}

			showQuery();
			break;
		}
	}
	
	void showQuery() {
		final Dialog mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		mDialog.setContentView(R.layout.dialog_query);
		mDialog.findViewById(R.id.left).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDialog.dismiss();
					}
				});
		mDialog.findViewById(R.id.right).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDialog.dismiss();
						sendDelHttpRequest();
					}
				});
		mDialog.show();
	}
	
	private void sendDelHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				TLog.d(TAG, "response=" + response);
				Resp ruser = JSON.parseObject(response, Resp.class);

				if (ruser.getState().equals("1")) {
					mArray.removeAll(mArray);
					mAdapter.notifyDataSetChanged();
					sendHttpRequest();
				} 
				else if (ruser.getState().equals("2")) 
				{showExitDialog();} else {
					ToastUtil.showToastWithAlertPic(ruser.getMessage());
				}
			}
		};

		StringBuffer buffer = new StringBuffer();
		for(String item : mSelectArray)
		{
			if(buffer.length() > 0) buffer.append(",");
			buffer.append(item);
		}
		
		StringBuffer device = new StringBuffer();
		for(String item : mSelectDevice)
		{
			if(device.length() > 0) device.append(",");
			device.append(item);
		}
		
		RequestParams params = new RequestParams();
		params.put("act", "operateInfo");
		params.put("userid", PreferencesUtils.getString(this, "userid"));
		params.put("type", "9");
		params.put("infoid", buffer.toString());
		params.put("deviceid", device.toString());
		
		MgqRestClient.get(Constants.INFOMGT, params, loginHandler);
	}
	
}
